<?php
/**
 * Medical Center - Monitoring Main Screen
 * This module will display the current medical center monitoring it
 * can be updated
 * 
 * 
 * @author Xavier VILAIN
 * @package Nawa\MedicalStudy\MedicalCenter\Monitoring
 * @license #license-nawa#
 * 
 */

use Fox\Html\Input;
use Nawa\MedicalStudy\Metadata;
use Nawa\MedicalStudy\MedicalCenter\Monitoring\Survey\Question;
use Fox\Html\Block;
use Nawa\MedicalStudy\MedicalCenter\Monitoring\Partner;
use Fox\Behaviors;
use Fox\Html\Button;
use Fox\Core\Web\Application\Renderer\Mobile;
use Fox\Generator;
use Nawa\MedicalStudy\MedicalCenter\Monitoring;
use Fox\Html\Screen;
$xview = Xview::instance();
$msid = $xview->val('msid');
$mcid = $xview->val('mcid');
$monitoringid = $xview->val('monitoringid');
$mode = $xview->val('mode');
$keys = array('msid' => $msid,'mcid' => $mcid,'monitoringid' => $monitoringid);
$ms = $xview->component('medicalstudies','object',$keys);

$nbCenters = $ms->countMedicalCentersPartners();
$centerPartner = $ms->findMedicalCentersPartners($ms->getInLineId().':'.$mcid);
$medicalCenter = $centerPartner->medicalCenter();
if($mode == 'create' || empty($monitoringid)) {
	$mode = 'create';
	$exist = false;
	$monitoring = new Nawa\MedicalStudy\MedicalCenter\Monitoring();
} else {
	$monitoring = $centerPartner->findMonitorings($centerPartner->getInLineId().':'.$monitoringid);
	$mode = 'update';
	$exist = true;
}
$data = $monitoring->getData();
$data['gPartners'] = $monitoring->partnersData();
foreach($data['gPartners'] as $partnerData) {
	$partners[$partnerData['customerid']] = $monitoring->getInLineId().':'.$partnerData['customerid'];
}
// Bread Crumb
$crumbs = $xview
	->component('medicalstudies','breadcrumb',
	array('deepness' => 5,
		  'customerid' => $ms->customer()->getId(),
		  'customer_name' => $ms->customer()->name1,
		  'msReference' => $ms->reference,
		  'msid' => $ms->getId(),
		  'msCenterCount' => $nbCenters,
		  'mcid' => $mcid,
		  'mcLabel' => $medicalCenter->label(),
		  'mcMonitoringCount' => $centerPartner->countMonitorings(),
		  'monitoring' => ($monitoring->exists()) ? $monitoring : null,
		  'type' => Monitoring::BREADCRUMB_NODE
	)
);
$screen = new Screen('sCenter',$mode);
$screen->breadcrumb()->crumbs($crumbs);

// Header Block
$blHeader = $xview->component('medicalstudies','monitoringHeader',$keys);
$blHeader->item('monitoringid')->input(false);
if(!$monitoring->exists()) {
	$blHeader->item('status')->input(false);
	$blHeader->item('monitoringid')
		->hidden()
		->excluded();

} else {
	$blHeader->item('status')->unsetOption(array(Monitoring::STATUS_NEW));
}
$screen->add($blHeader);

// Partner Block
if($exist) {
	// Add Authorization Check
	$blPartners = $xview->module(Generator::url('medicalstudies',
									'medicalcenters',
									'monitoring_partners'
									,$keys));
	$screen->add($blPartners);
	// Patient Block
	$blPatients  = $xview->module(Generator::url('medicalstudies',
									'medicalcenters',
									'patients'
									,$keys));
	$blPatients->item('patients')->footer()->remove('addpatient');
	$blPatients->collapsed(false);
	$screen->add($blPatients);
	// Fix the Monitoring Type TODO add a the capability to change it if progress is equal = 0
	$blHeader->add(new Input('type'))->hidden();
	$blHeader->item('category')->input(false);
	$status = $xview->val('status',$monitoring->status);
	// Build CheckList Form
	foreach($monitoring->surveys() as $survey) {
		/* @var $survey Nawa\MedicalStudy\MedicalCenter\Monitoring\Survey */
		$surveyTemplate = $survey->template();
		$blSurvey = new Block('survey_'.$survey->surveyid,$surveyTemplate->label());
		$initialize = null;
		if($monitoring->isValitated($status)) {
			$blSurvey->cssClass('readonly');
			$readonly = true;
		} else {
			$readonly = false;
		}
		// Retrieve all question answser to initialize the survey
		foreach($survey->questions() as $question) {
			$questions[$question->questionid] = $question;
			$initialize[$question->questionid] = array('default' => $question->answers,'readonly' => $readonly);
		}
		$surveyid = $survey->surveyid;
		$blSurvey->add(new \Fox\Html\Html($survey->surveyid,$survey->render($initialize)));
		$blSurvey->collapsed($readonly);
		
		$screen->add($blSurvey);
	}
	if($monitoring->isValitated($status)) {
		// Add Generate PDF button
		$screen->add(new Button('generate',
					Generator::url('medicalstudies','medicalcenter','pdf',
						array_merge(array('xvtrs' => 'none'),$keys)),
						Msg(Nawa\Messages::BUNDLE,Nawa\Messages::PDF_EDITION)))
						->color(Button::COLOR_BLUE);
		// Read Only Partners
		$blPartners->cssClass('readonly')
			->item('gPartners')
				->remove('fo_gPartners')
				->fieldcat()
					->field('coche')->hidden()->parentObject()
					->field('bupload')->hidden();
		// Read Only Patients
		$blPatients->cssClass('readonly')
				->item('patients')
				->fieldcat()
					->field('iedit')
						->hidden();
		// Date Not Changeable
		$blHeader->item('monitoring_date')->input(false);
		
	} else {
		$screen->button(new Button('delete','?'),0)
				->color(Button::COLOR_RED)
				->behaviors(Behaviors::action(
					Generator::url('medicalstudies','medicalcenter','monitoring_delete',$keys),
					true
					)
				)
				;
	}
}
$screen->initialize($data);
if($screen->submitted()) {
	$fields = $screen->get();
	if(!$screen->errors())
	{
		$typeByCategory = $ms->metadata(Metadata::CHECKLISTS)->parse(true);
		if(!$monitoring->exists() || empty($fields['type'])) {
			if(!empty($typeByCategory['category_'.$fields['category']])) {
				$fields['type'] = $typeByCategory['category_'.$fields['category']];
			}
		}
		try {
			$fields['udate'] = Monitoring::sqlDateTime(time());
			$fields['uname'] = User::current()->getId();
			if(!$monitoring->exists()) {
				$infos = \Fox\Dao::infos(Monitoring::className());
				$handle = $infos->handle();
				$handle->beginTransaction();
				$fields['mcid'] = $mcid;
				$fields['msid'] = $msid;
				$fields['status'] = Monitoring::STATUS_WIP;
				$monitoring->setFields($fields);
				// Add current user has a partner
				$partner = new Partner();
				$partner->setFields(array('msid' => $msid,
										  'mcid' => $mcid,
										  'customerid' => User::current()->contactId(),
										  'role' => Monitoring::ROLE_DEFAULT,
										  'udate' => Monitoring::sqlDateTime(time()),
										  'uname' => User::current()->getId()));
				$monitoring->addToPartners($partner);
				$monitoring->create();
				// Add the Survey in the survey list
				$monitoring->createSurveyFromTemplate();
				$handle->commit();
				$keys['monitoringid'] = $monitoring->monitoringid;
				$dateLabel = Fox\Utilities\Dates::dateTimeToFullString($fields['monitoring_date']);
				Fox\Message::Success(Msg(Nawa\Messages::BUNDLE,Nawa\Messages::MONITORING_OF_HAS_CREATED,$dateLabel));
				$screen->redirect(Generator::url('medicalstudies','medicalcenters','monitoring',$keys));
			} else {
				$monitoring->setFields($fields);
				// Update Partners
				if(is_array($fields['gPartners'])) {
					foreach($fields['gPartners'] as $partnerData) {
						if(!empty($partners[$partnerData['customerid']])) {
							unset($partners[$partnerData['customerid']]);
						}
					}
				}
				
				// Update Survey ?
				$nbOfAnwseredQuestion = 0;
				foreach($_POST as $fielname => $value) {
					if(substr($fielname,0,3) == 'qa_') {
						$questionid = substr($fielname,3);
						$version = !empty($_POST['qv_'.$questionid]) ? $_POST['qv_'.$questionid] : null;
						// It's the anwser to a question
						try {
							if(!empty($value)) {
								$nbOfAnwseredQuestion++;
							}
							
							if(!empty($questions[$questionid])) {
								$questions[$questionid]->setFields(array('answers' => $value,'version' => $version));
								// @TODO add update the version number
								$questions[$questionid]->update();
							} else {
								// Add Question/Anwser to the survey
								$question = new Question();
								$question->setFields(array('msid' => $msid,
														'mcid' => $mcid,
														'monitoringid' => $monitoringid,
														'surveyid' => $surveyid,//TODO make handle multiple survey
														'version' => $version,
														'questionid' => $questionid,
														'answers' => $value)
								);
								$question->create();
								$questions[$questionid] = $question;
							}
						} catch(\Fox\Object\Exception\Save $e) {
							Fox\Message::Error($e);
						}
					}
				}
				$nbOfQuestions = $surveyTemplate->countQuestions();
				if($nbOfQuestions > 0) {
					$monitoring->progress = $nbOfAnwseredQuestion/$nbOfQuestions * 100;
				}
				if($monitoring->isValitated($status)) {
					$monitoring->progress = 100;
				}
				if(is_array($partners)) {
					if(count($partners) == $monitoring->countPartners()) {
						$screen->initialize(array('gPartners' => $data['gPartners']));
						\Fox\Message::Error(Msg(Nawa\Messages::BUNDLE,Nawa\Messages::ERR_PARTNERS_CANT_REMOVE_ALL));
					} else {
						foreach($partners as $partnerInlineId) {
							$partner = $monitoring->findPartners($partnerInlineId);
							$monitoring->deleteFromPartners($partner);
						}
					}
				}
				if(!$screen->errors()) {
					$monitoring->update();
					Fox\Message::Success(Msg(Nawa\Messages::BUNDLE,Nawa\Messages::MONITORING_UPDATED));
				}
			}
		}
		catch (Fox\Object\Exception\Save $e) {
			Fox\Message::Error($e);
		}
		catch (\Exception $e) {
			Fox\Message::Error($e);
		}
	}
}
echo $screen->display();